<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Client extends CI_Controller {

    function __construct() {

        @session_start();
        parent::__construct();
		
		$this->load->model('client_model');
        $this->load->model('circle_model');
		
		$this->load->helper('my_html_helper');
		
		
        $this->load->library('session');
		$this->load->library('competence_lib');
		
		$this->load->model('nationality_model');
        $this->load->model('importance_of_customers_model');
		$this->load->model('nationality_model');
		$this->load->model('client_model');
		$this->load->model('importance_of_customers_model');
        
        $this->load->model('nationality_model');					
		$this->load->model("role_model");
				
    }

    public function data_entry() {

        $html = $this->init("客戶資料輸入", "jquery,client,client_ready,date,address", "form");
        $this->load->model('importance_of_customers_model');
        $html["importance_of_customers"] = $this->importance_of_customers_model->get_all();
        $this->load->model('nationality_model');
        $html["nationality"] = $this->nationality_model->get_all();
        $this->load->model('customer_source_model');
        $html["customer_source"] = $this->customer_source_model->get_all();
        $this->load->model('building_name_model');
        $html["building_name"] = $this->building_name_model->get_all();
        $this->load->model('type_of_company_model');
        $html["type_of_company"] = $this->type_of_company_model->get_all();
        $this->load->model('title_model');
        $html["title"] = $this->title_model->get_all();
        $this->load->model('customer_type_model');
        $html["customer_type"] = $this->customer_type_model->get_all();
        $this->load->model('contact_usual_holiday_model');
        $html["contact_usual_holiday"] = $this->contact_usual_holiday_model->get_all();
        $this->load->model('address_city_model');
        $html["address_city"] = $this->address_city_model->get_all();
        $this->load->model('address_county_model');
        $html["address_county"] = $this->address_county_model->get_by_id('1');

        $this->load->model('users_model');
        $html["users"] = $this->users_model->get_all_users();

        $this->load->model('object_name_model');
        $html["object_names"] = $this->object_name_model->get_all();

        $this->load->model('building_name_model');
        $html["building_names"] = $this->object_name_model->get_all();
        $t = date("ymdhis");

        $html["ref_client_verify_code"] = MD5($t);

        $this->load->model("users_model");
        $this->load->library('session');
        $c_ss = $this->session->all_userdata();
        $_head_info = $this->users_model->get_user_by_user('劉陳傳');

        //權限id
        //接待人	,	經紀人
        $html["front_man"] = $c_ss["users_id"];
        $html["broker"] = $c_ss["users_id"];
        //主管
        $html["head"] = $_head_info->result();

        $this->load->view('client/c_data_entry', $html);
    }

    public function save_client_id() {

        @session_start();

        if ($_POST["is_del"] == 0) {

            $_str = explode(',', $_POST["id"]);
            foreach ($_str as $num => $val) {
                $_SESSION["client_page"][$val] = 1;
            }

        } elseif ($_POST["is_del"] == 1) {

            $_SESSION["client_page"][$_POST["id"]] = 0;

        }

    }

    public function client_page_clean() {
        @session_start();
        session_unset($_SESSION["client_page"]);
        session_destroy($_SESSION["client_page"]);
    }

    public function get_save_client_id() {

        @session_start();

        if (!empty($_GET["id"]) AND $_GET["id"] != 0) {
            if (empty($_SESSION["client_page"][$_GET["id"]])) {
                $_SESSION["client_page"][$_GET["id"]] = 1;
            } else {
                $_SESSION["client_page"][$_GET["id"]] = 0;
            }
        }
        //echo $_GET["id"];
        //print_r($_SESSION);
    }

    public function check_buidling_name($field_name, $value) {
        //簡查大樓名稱
        $this->load->model('check_model');
        $this->check_model->set_table_name("h_building_name");
        $this->check_model->set_key_name("building_name_id");
        $_id = $this->check_model->check_building_name_exist($field_name, $value);
        return $_id;
    }

    public function data_entry_submit() {

        
        $data['name'] = $this->input->post('name');
        $data['english_name'] = $this->input->post('english_name');
        $data['recommended'] = $this->input->post('recommended');
        $data['importance'] = $this->input->post('importance');

        //$nation=($_POST['nationality'])?$_POST['nationality']:1;

        $data['nationality'] = $_POST['nationality'];
        $data['english_name'] = $this->input->post('english_name');
        $data['ref_client_verify_code'] = $this->input->post('ref_client_verify_code');

        $data['sex'] = $this->input->post('sex');
        $data['mobile'] = $this->input->post('mobile');
        if ($this->input->post('mobile1') != "")
            $data['mobile1'] = $this->input->post('mobile1');
        if ($this->input->post('mobile2') != "")
            $data['mobile2'] = $this->input->post('mobile2');
        $data['send_sms'] = $this->input->post('send_sms');
        if ($this->input->post('send_sms1') != "")
            $data['send_sms1'] = $this->input->post('send_sms1');
        if ($this->input->post('send_sms2') != "")
            $data['send_sms2'] = $this->input->post('send_sms2');
        $data['home_phone'] = $this->input->post('home_phone');
        if ($this->input->post('home_phone1') != "")
            $data['home_phone1'] = $this->input->post('home_phone1');
        if ($this->input->post('home_phone2') != "")
            $data['home_phone2'] = $this->input->post('home_phone2');
        $data['company_phone'] = $this->input->post('company_phone');
        if ($this->input->post('company_phone1') != "")
            $data['company_phone1'] = $this->input->post('company_phone1');
        if ($this->input->post('company_phone2') != "")
            $data['company_phone2'] = $this->input->post('company_phone2');
        $data['company_phone_ext'] = $this->input->post('company_phone_ext');
        if ($this->input->post('company_phone_ext1') != "")
            $data['company_phone_ext1'] = $this->input->post('company_phone_ext1');
        if ($this->input->post('company_phone_ext2') != "")
            $data['company_phone_ext2'] = $this->input->post('company_phone_ext2');
        $data['email'] = $this->input->post('email');
        if ($this->input->post('email1') != "")
            $data['email1'] = $this->input->post('email1');
        if ($this->input->post('email2') != "")
            $data['email2'] = $this->input->post('email2');
        $data['send_email'] = $this->input->post('send_email');
        if ($this->input->post('send_email1') != "")
            $data['send_email1'] = $this->input->post('send_email1');
        if ($this->input->post('send_email2') != "")
            $data['send_email2'] = $this->input->post('send_email2');
        $data['fax'] = $this->input->post('fax');
        if ($this->input->post('fax1') != "")
            $data['fax1'] = $this->input->post('fax1');
        if ($this->input->post('fax2') != "")
            $data['fax2'] = $this->input->post('fax2');
        $data['customer_source'] = $this->input->post('customer_source');
        $data['home_address'] = $this->input->post('home_address');

        if ($this->input->post('home_address1') != "")
            $data['home_address1'] = $this->input->post('home_address1');
        if ($this->input->post('home_address2') != "")
            $data['home_address2'] = $this->input->post('home_address2');

        /*         * ************************************************************** */
        $data['home_building_name'] = $this->input->post('home_building_name');
        $data['home_building_name1'] = $this->input->post('home_building_name1');
        $data['home_building_name2'] = $this->input->post('home_building_name2');
		
		
		
		
        /*
        if ($this->input->post('home_building_name') != "") {
            $re_id = $this->check_buidling_name("value", $data['home_building_name']);
            $data['home_building_name'] = $re_id;
            //$this->input->post('home_building_name');
        }

        if ($this->input->post('home_building_name1') != "") {
            $re_id1 = $this->check_buidling_name("value", $data['home_building_name1']);
            $data['home_building_name1'] = $re_id1;
            //$this->input->post('home_building_name1');
        }

        if ($this->input->post('home_building_name2') != "") {
            $re_id2 = $this->check_buidling_name("value", $data['home_building_name2']);
            $data['home_building_name2'] = $re_id2;
            //$this->input->post('home_building_name2');
        }
        /
        /*         * ************************************************************** */
        $data['home_send_publication'] = $this->input->post('home_send_publication');
        if ($this->input->post('home_send_publication1') != "")
            $data['home_send_publication1'] = $this->input->post('home_send_publication1');
        if ($this->input->post('home_send_publication2') != "")
            $data['home_send_publication2'] = $this->input->post('home_send_publication2');
        $data['company_name'] = $this->input->post('company_name');
        if ($this->input->post('company_name1') != "")
            $data['company_name1'] = $this->input->post('company_name1');
        if ($this->input->post('company_name2') != "")
            $data['company_name2'] = $this->input->post('company_name2');
        $data['type_of_company'] = $this->input->post('type_of_company');
        if ($this->input->post('type_of_company1') != "")
            $data['type_of_company1'] = $this->input->post('type_of_company1');
        if ($this->input->post('type_of_company2') != "")
            $data['type_of_company2'] = $this->input->post('type_of_company2');
        $data['unicode'] = $this->input->post('unicode');
        if ($this->input->post('unicode1') != "")
            $data['unicode1'] = $this->input->post('unicode1');
        if ($this->input->post('unicode2') != "")
            $data['unicode2'] = $this->input->post('unicode2');
        $data['department'] = $this->input->post('department');
        if ($this->input->post('department1') != "")
            $data['department1'] = $this->input->post('department1');
        if ($this->input->post('department2') != "")
            $data['department2'] = $this->input->post('department2');
        $data['title'] = $this->input->post('title');
        if ($this->input->post('title1') != "")
            $data['title1'] = $this->input->post('title1');
        if ($this->input->post('title2') != "")
            $data['title2'] = $this->input->post('title2');
        $data['category'] = $this->input->post('category');
        if ($this->input->post('category1') != "")
            $data['category1'] = $this->input->post('category1');
        if ($this->input->post('category2') != "")
            $data['category2'] = $this->input->post('category2');
        $data['company_address'] = $this->input->post('company_address');
        if ($this->input->post('company_address1') != "")
            $data['company_address1'] = $this->input->post('company_address1');
        if ($this->input->post('company_address2') != "")
            $data['company_address2'] = $this->input->post('company_address2');

        $data['company_building_name'] = $this->input->post('company_building_name');
        if ($this->input->post('company_building_name1') != "")
            $data['company_building_name1'] = $this->input->post('company_building_name1');
        if ($this->input->post('company_building_name2') != "")
            $data['company_building_name2'] = $this->input->post('company_building_name2');
        $data['company_send_publication'] = $this->input->post('company_send_publication');
        if ($this->input->post('company_send_publication1') != "")
            $data['company_send_publication1'] = $this->input->post('company_send_publication1');
        if ($this->input->post('company_send_publication2') != "")
            $data['company_send_publication2'] = $this->input->post('company_send_publication2');
        $data['company_website'] = $this->input->post('company_website');
        if ($this->input->post('company_website1') != "")
            $data['company_website1'] = $this->input->post('company_website1');
        if ($this->input->post('company_website2') != "")
            $data['company_website2'] = $this->input->post('company_website2');
        $data['front_man'] = $this->input->post('front_man');
        $data['head'] = $this->input->post('head');
        $data['original_broker'] = $this->input->post('original_broker');
        $data['broker'] = $this->input->post('broker');
        $data['birthday'] = $this->input->post('birthday');
        if ($this->input->post('birthday') != "") {
            $t = explode("/", $this->input->post('birthday'));
            $data['birthday_int'] = mktime(0, 0, 0, $t[1], $t[2], $t[0]);
        }
        $data['gifts'] = $this->input->post('gifts');
        $data['id_number'] = $this->input->post('id_number');
        $data['usually_contact'] = $this->input->post('usually_contact');
        if ($this->input->post('usually_contact1') != "")
            $data['usually_contact1'] = $this->input->post('usually_contact1');
        if ($this->input->post('usually_contact2') != "")
            $data['usually_contact2'] = $this->input->post('usually_contact2');
        $data['usually_start_time'] = $this->input->post('usually_start_time');
        if ($this->input->post('usually_start_time1') != "")
            $data['usually_start_time1'] = $this->input->post('usually_start_time1');
        if ($this->input->post('usually_start_time2') != "")
            $data['usually_start_time2'] = $this->input->post('usually_start_time2');
        $data['usually_end_time'] = $this->input->post('usually_end_time');
        if ($this->input->post('usually_end_time1') != "")
            $data['usually_end_time1'] = $this->input->post('usually_end_time1');
        if ($this->input->post('usually_end_time2') != "")
            $data['usually_end_time2'] = $this->input->post('usually_end_time2');
        $data['holidays_contact'] = $this->input->post('holidays_contact');
        if ($this->input->post('holidays_contact1') != "")
            $data['holidays_contact1'] = $this->input->post('holidays_contact1');
        if ($this->input->post('holidays_contact2') != "")
            $data['holidays_contact2'] = $this->input->post('holidays_contact2');
        $data['holidays_start_time'] = $this->input->post('holidays_start_time');
        if ($this->input->post('holidays_start_time1') != "")
            $data['holidays_start_time1'] = $this->input->post('holidays_start_time1');
        if ($this->input->post('holidays_start_time2') != "")
            $data['holidays_start_time2'] = $this->input->post('holidays_start_time2');
        $data['holidays_end_time'] = $this->input->post('holidays_end_time');
        if ($this->input->post('holidays_end_time1') != "")
            $data['holidays_end_time1'] = $this->input->post('holidays_end_time1');
        if ($this->input->post('holidays_end_time2') != "")
            $data['holidays_end_time2'] = $this->input->post('holidays_end_time2');
        $data['background_and_features'] = $this->input->post('background_and_features');
        $data['ref_client_verify_code'] = $this->input->post('ref_client_verify_code');
		
		
		$data['sercet_level'] = $this->input->post('sercet_level');
		$data['is_public'] = $this->input->post('is_public');
		$data['important'] = $this->input->post('important');
		$data['is_see'] = $this->input->post('is_see');
		$data['ctime'] = time();
        $data['mtime'] = time();
		
		//print_r($data);

        $this->client_model->insert($data);
		redirect("/client/data_query");
        //print_r($_POST);
        //echo $this->db->last_query();die();
        //print_r($_POST);
        //echo '<br>';
        //echo '<br>';
        //echo '<br>';
        /*/print_r($_POST["contact"]);

        if ($return_result > 0) {

            $this->load->model('building_name_model');
            $hbn['value'] = $this->input->post('home_building_name');
            $hbn['explanation'] = $this->input->post('home_building_name');
            $this->building_name_model->is_add($hbn);

            $cbn['value'] = $this->input->post('company_building_name');
            $cbn['explanation'] = $this->input->post('company_building_name');

            $this->building_name_model->is_add($cbn);

            redirect("/client/data_query_results/new_insert");
        } else {
            echo "插入失敗";
        }
        
		 * */
    }

	

    public function data_entry_contact_submit() {

        if ($_POST) {
            $ref_client_verify_code = $this->input->post("ref_client_verify_code");
            foreach ($_POST["contact"] as $icount => $data) {
                $this->client_model->insert_contact($data, $ref_client_verify_code);
            }
        }
    }

    public function data_entry_relationship_submit2() {

        //print_r($_POST);
        $ref_client_verify_code = $this->input->post("ref_client_verify_code");

        if (!empty($ref_client_verify_code)) {

            $name = $this->input->post("name");
            $english_name = $this->input->post("english_name");
            $sex = $this->input->post("sex");

            $mobile = $this->input->post("mobile");
            $home_phone = $this->input->post("home_phone");
            $company_phone = $this->input->post("company_phone");
            $fax = $this->input->post("fax");

            $home_address = $this->input->post("home_address");
            $company_address = $this->input->post("company_address");

            $data = array("name" => $name, "english_name" => $english_name, "sex" => $sex, "mobile" => $mobile, "home_phone" => $home_phone, "company_phone" => $company_phone, "fax" => $fax, "home_address" => $home_address, "company_address" => $company_address);

            $this->client_model->insert_relationship($data, $ref_client_verify_code);
        }
    }

    public function data_entry_relationship_submit() {

        if (!empty($_POST)) {
            $ref_client_verify_code = $this->input->post("ref_client_verify_code");
            $this->client_model->insert_relationship($_POST, $ref_client_verify_code);
        }
    }

    public function data_query() {

        $html = $this->init("客戶資料查詢", "jquery,client,client_data_query_ready,date,address", "form");
        $this->load->model('importance_of_customers_model');
		$this->load->model('address_county_model');
		$this->load->model('users_model');
		$this->load->model('address_city_model');
		$this->load->model('customer_source_model');
		$this->load->model('nationality_model');
		$this->load->model('building_name_model');
		$this->load->model('type_of_company_model');


        $html["importance_of_customers"] = $this->importance_of_customers_model->get_all();
        $html["nationality"] = $this->nationality_model->get_all();
        $html["building_name"] = $this->building_name_model->get_all();
        $html["type_of_company"] = $this->type_of_company_model->get_all();
        $html["customer_source"] = $this->customer_source_model->get_all();
        $html["address_city"] = $this->address_city_model->get_all();
        $html["users"] = $this->users_model->get_user();
        $html["address_county"] = $this->address_county_model->get_by_id('1');
        $html["search_page"] = $this->load->view('client_data_query', $html,true);
		
		
		$html["post_data"] = $_POST;
        $this->load->view('crid/clients_crid', $html);

    }

 	

    public function client_josn() {


        $this->load->model('client_model');
        $query = trim($this->input->get('query'));
        $client = $this->client_model->get_client_recommended($query);
        //echo $this->db->last_query();echo "<br/>";
        echo urldecode(json_encode($client));
    }


    public function object_josn() {

        
        $this->load->model('client_model');
        $query = trim($this->input->get('query'));
        $client = $this->client_model->get_object_recommended($query);
        //echo $this->db->last_query();echo "<br/>";
        

        die();
        echo urldecode(json_encode($client));
    }

    public function demand_client() {
        $this->load->model('client_model');
        $query = trim($this->input->get('query'));
        $client = $this->client_model->get_demand_client($query);
        echo urldecode(json_encode($client));
    }

    public function ctest() {

        $user_purview = check_broker_is_visible();
        print_r($user_purview);
        if (!$user_purview) {
            echo $this->login_lib->users_id();
            //$this->set_where('front_man,broker', $this->login_lib->users_id());
        }


    }


    public function client_contact() {

        $this->load->model('client_model');
        $query = trim($this->input->get('query'));
        $user_purview = check_broker_is_visible();
        $client;
        if (!$user_purview) {
            //經紀人是否可見
            $client = $this->client_model->get_demand_client_broker_no_visible($query);
        }else{

            $client = $this->client_model->get_demand_client_broker_visible($query);
        }

        //$client = $this->client_model->get_demand_client_broker_no_visible($query);
        echo urldecode(json_encode($client));
    }

    public function get_client_contact_json() {

        $this->load->model('client_model');
        $query = trim($this->input->get('query'));
        $client = $this->client_model->get_client_contact($query);
        echo urldecode(json_encode($client));
    }

    public function get_contact_json() {

        $this->load->model("client/contact", 'contact');
        $query = trim($this->input->get('query'));
        $client = $this->contact->get_contact_json($query);
        echo urldecode(json_encode($client));
    }

    public function object_client() {

        $this->load->model('client_model');
        $query = trim($this->input->get('query'));
        $client = $this->client_model->get_object_client($query);

        echo urldecode(json_encode($client));
    }

    public function client_name_josn() {
        $this->load->model('client_model');
        $query = trim($this->input->post('name'));
        if ($query != "") {
            $c = $this->client_model->get_client_name_count($query);
            //echo $this->db->last_query();
            if ($c > 0) {
                $client = $this->client_model->get_client_name($query);
                echo urldecode(json_encode($client));
            } else {
                echo "N";
            }
        } else {
            echo "N";
        }
    }

    public function client_sf_josn() {

        

        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
        $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'client_id';
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';

        $query = isset($_POST['query']) ? $_POST['query'] : false;
        $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : false;

        $name = isset($_POST['name']) ? $_POST['name'] : false;
        $recommended = isset($_POST['recommended']) ? $_POST['recommended'] : false;
        $importance = isset($_POST['importance']) ? $_POST['importance'] : false;
        $nationality = isset($_POST['nationality']) ? $_POST['nationality'] : false;

        $keywords = isset($_POST['keywords']) ? $_POST['keywords'] : false;
        $broker = isset($_POST['broker']) ? $_POST['broker'] : false;
        $home_address = isset($_POST['home_address']) ? $_POST['home_address'] : false;
		
        $mobile = isset($_POST['mobile']) ? $_POST['mobile'] : false;		
        $customer_source = isset($_POST['customer_source']) ? $_POST['customer_source'] : false;
        $category = isset($_POST['category']) ? $_POST['category'] : false;
        $company_name = isset($_POST['company_name']) ? $_POST['company_name'] : false;
        $building_name = isset($_POST['building_name']) ? $_POST['building_name'] : false;
        //$building_name = isset($_POST['building_name']) ? $_POST['building_name'] : false;

        $sctime = isset($_POST['sctime']) ? $_POST['sctime'] : false;
        $ectime = isset($_POST['ectime']) ? $_POST['ectime'] : false;

        $sbirthday = isset($_POST['sbirthday']) ? $_POST['sbirthday'] : false;
        $ebirthday = isset($_POST['ebirthday']) ? $_POST['ebirthday'] : false;

        $send_publication = isset($_POST['send_publication']) ? $_POST['send_publication'] : false;
        $send_email = isset($_POST['send_email']) ? $_POST['send_email'] : false;
        $gifts = isset($_POST['gifts']) ? $_POST['gifts'] : false;

        $where = array();
        $where_flag = TRUE;

        if ($gifts) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }

            $where[]= " ( `gifts` like '%" . $gifts . "%' ) ";
        }

        if ($send_email) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }

            $where[]=   " (  `send_email` = '" . $send_email . "' ".
                                    " OR `send_email1` = '" . $send_email . "' ".
                                    " OR `send_email2` = '" . $send_email . "' ) ";
        }

        if ($send_publication) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }

            $where[]= 
                " ( `home_send_publication` = '" . $send_publication . "' ".
                " OR `home_send_publication1` = '" . $send_publication . "' ".
                " OR `home_send_publication2` = '" . $send_publication . "' ".

                " OR `company_send_publication` = '" . $send_publication . "' ".
                " OR `company_send_publication1` = '" . $send_publication . "' ".
                " OR `company_send_publication2` = '" . $send_publication . "' ) ";
            
        }

        if ($sbirthday OR $ebirthday) {

            $ebirthday = strtotime($ebirthday);
            $sbirthday = strtotime($sbirthday);

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }

            $where[]=   " ( `birthday_int` >= '" . $sbirthday . "' " . 
                        " AND `birthday_int` <= '" . $ebirthday . "' ) ";
        }

        if ($ectime OR $sctime) {

            $ectime = strtotime($ectime);
            $sctime = strtotime($sctime);

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }

            $where[]=   " ( `ctime` >= '" . ($sctime-(60*24*60)) ."' ". 
                        "  AND `ctime` <= '" . ($ectime+(60*24*60) ). "' ) ";
        }

        if ($building_name) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }

            $where[] =   " ( `home_building_name` LIKE '%" . $building_name . "%' ".
                        " OR `home_building_name1` LIKE '%" . $building_name . "%' ".
                        " OR `home_building_name2` LIKE '%" . $building_name . "%' ) ";
        }

        if ($company_name) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }
            $where[]= 
                    "  ( `company_name1` LIKE '%" . $company_name . "%' ".
                    " OR `company_name2` LIKE '%" . $company_name . "%' ".
                    " OR `company_name` LIKE '%" . $company_name . "%' ) ";
        }

        if ($category) {

            $_cc  =  explode(",", $category);

            $category_flg=true;
            $category_str=' ( ';


            foreach($_cc as $_aa => $vv ){

                if(strlen($vv)>2){
                    // if ($where_flag) {
                    //     $where .= " WHERE ";
                    //     $where_flag = false;
                    // } else {
                    //     $where .= " OR ";
                    // }
                    if ($category_flg) {

                            $category_flg=false;
                            $category_str.= 
                                    "  `category`    LIKE '%" . trim($vv) . "%' ".
                                    " OR `category1` LIKE '%" . trim($vv) . "%' ".
                                    " OR `category2` LIKE '%" . trim($vv) . "%' ";
                    }else{
                            $category_str.= 
                                    " OR `category`  LIKE '%" . trim($vv) . "%' ".
                                    " OR `category1` LIKE '%" . trim($vv) . "%' ".
                                    " OR `category2` LIKE '%" . trim($vv) . "%' ";

                    }
                }
            }

            $category_str.=' ) ';
            $where[]=$category_str;

        }

        $this->load->model("insert_model");

        if ($customer_source) {
            $customer_source_flg=true;
            $customer_source_flg_str=' ( ';
          //$this->insert_model->insert("h_sql" , array("SQL"=>$customer_source));
            $c_s_s_res = $this->customer_source_seslove($customer_source);

            foreach( $c_s_s_res as $_k => $_v){

                // if ($where_flag) {

                //     $where .= " WHERE ";
                //     $where_flag = false;

                // } else {

                //     $where .= " OR ";

                // }
                if($customer_source_flg){
                    $customer_source_flg=false;
                    $customer_source_flg_str.= "  `customer_source` = '" . $_k . "'  ";
                }else{
                    $customer_source_flg_str.= " OR `customer_source` = '" . $_k . "'  ";
                }
                
            }

            $customer_source_flg_str.=' ) ';
            $where[]=$customer_source_flg_str;

        }


        if ($mobile) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }

            $where[]= 
            "  ( `mobile` LIKE '%" . $mobile . "%' ".
            " OR  `mobile1` LIKE '%" . $mobile . "%' ".
            " OR  `mobile2` LIKE '%" . $mobile . "%' ".

            " OR  `home_phone` LIKE '%" . $mobile . "%' ".
            " OR  `home_phone1` LIKE '%" . $mobile . "%' ".
            " OR  `home_phone2` LIKE '%" . $mobile . "%' ".

            " OR  `company_phone` LIKE '%" . $mobile . "%' ".
            " OR  `company_phone1` LIKE '%" . $mobile . "%' ".
            " OR  `company_phone2` LIKE '%" . $mobile . "%' ) ";

        }

        if ($home_address) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }
            $where[]= " ( `home_address` LIKE '%" . $home_address . "%' ) ";
        }

        if ($keywords) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " OR ";
            // }
            $where[]= 
            "   (  `background_and_features` LIKE '%" . $keywords . "%' ".
            "  OR `email` LIKE '%" . $keywords . "%' ".
            "  OR `email1` LIKE '%" . $keywords . "%' ".
            "  OR `email2` LIKE '%" . $keywords . "%' ) ";

            // $c_s_s_res = $this->customer_source_seslove($keywords);
            // //去找看看有有一樣的客戶來源
            // foreach( $c_s_s_res as $_k => $_v){

            //     // if ($where_flag) {

            //     //     $where .= " WHERE ";
            //     //     $where_flag = false;

            //     // } else {

            //     //     $where .= " OR ";

            //     // }

            //     $where[]= " ( `customer_source` LIKE '%" . $_k . "%' ) ";
            // }

        }

        if ($broker) {

        	//$this->load->model("users_model");
			//$users_data=$this->users_model->get_user_s_name($broker);


			//foreach($users_data->result() as $user ){

	            // if ($where_flag) {
	            //     $where .= " WHERE ";
	            //     $where_flag = false;
	            // } else {
	            //     $where .= " AND ";
	            // }


	            $where[]= " ( `broker` = '" . $broker . "' ) ";
			//}
        }

        if ($name) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " AND ";
            // }
            $where[]= " ( `name` LIKE '%" . $name . "%'  ) ";
        }

        if ($recommended) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " AND ";
            // }
            $where[]= " ( `recommended` LIKE '%" . $recommended . "%' ) ";
        }

        if ($importance) {
            $importance_flg=true;
            $ipo=' ( ';
            //$this -> circle_model -> insert_sql_where($str);

            $importance_array = explode(',', $importance);

            foreach ($importance_array as $key => $str) {

                //$this -> circle_model -> insert_sql_where($str);

                if (strlen($str)>2) {

                   if($importance_flg){
                        $importance_flg=false;
                        $ipo.= " `importance` = '".trim($str)."' " ;
                    }else{
                        $ipo.= " OR `importance` = '".trim($str) ."'   " ;
                    }

                    //$ipo .= "  `importance` = '" . trim($str) . "' OR ";
                }
            }

            $ipo.=' ) ';

            $where[]=$ipo;

        }

        if ($nationality){

            $stuednt_array = explode(",", $nationality);
            $nat_str_flg=true;
            $nat_str = ' ( ';


            foreach ($stuednt_array as $index => $value) {

                if ($value!=0) {
                    if($nat_str_flg){
                        $nat_str_flg=false;
                        $nat_str.= " `nationality` like '%".$value ."%' " ;
                    }else{
                        $nat_str.= " OR `nationality` like '%".$value ."%'   " ;
                    }
                    
                }   
            }

            $nat_str .= ' ) ';

            $where[]=$nat_str;
        }

        //經紀人是否可見
        $CI = &get_instance();
        $purview = $CI->login_lib->purview();
        $users_id = $CI->login_lib->users_id();

        $this->load->library('show_test');
        if (!$this->show_test->is_broker_visible()) {

            // if ($where_flag) {
            //     $where .= " WHERE ";
            //     $where_flag = false;
            // } else {
            //     $where .= " AND ";
            // }

            $where[] = " ( `broker` = '" . $users_id . "' ) ";
        }

        /*-------------*/
        $whr_str='';
        $asdqwe=true;

        foreach ($where as $key => $value) {
            if(strlen($value) > 5 ){

                   
                    
                if($asdqwe){
                    $asdqwe=false;
                    $whr_str.=$value;
                }else{
                    $whr_str.=' AND '.$value;
                }

                
            }
        }
        if( strlen($whr_str) > 5){
             //$whr_str.=' where ';
             $where= ' where '.$whr_str;
        }else{
            $where=$whr_str;
        }
        /////////////////////////////////////////////////////////////
        $this->load->model('importance_of_customers_model');
        $impo = $this->importance_of_customers_model->get_all();

        $this->load->model('importance_of_customers_model');
        $impo = $this->importance_of_customers_model->get_all();
        $impo_s = array();

        foreach ($impo as $key => $value) {
            $impo_s[$value->importance_of_customers_id] = $value->value;
        }

        $this->circle_model->insert_sql_where($where);

        $query = $this->client_model->client_for_crid($page, $rp, $sortname, $sortorder, $where);

        $client_array = $this->get_all_clients();

        //print_r($client_array);

        header("Content-type: application/json");

        $total_rows = $this->client_model->countRec("h_circle", $where);

        $jsonData = array('page' => $page, 'total' => $total_rows, 'rows' => array());

        //$html_chbox = '<input type=checkbox onClick=save_client(\'';
        
		$all_se =   $this->session->all_userdata();
		
        foreach ($query->result() as $row) {

            //$html_ck = $html_chbox . $row -> client_id . '\'); ';
            //$html_ck .= ' id=' . $row -> client_id;
            //$html_ck .= ' >';

            $broker_name = '';

            foreach ($client_array as $key => $_name) {

                //echo $key .'=>'. $_name;
                if ((int) $row->broker == $key) {
                    $broker_name = $_name;
                }
            }
			
			
			
			//林金龍說要的權限控管
			if($this->competence_lib->competence($row , $all_se)){
			
	            $entry = array('client_id' => $row->client_id, 'cell' => array(
	                    //$html_chbox.$row->client_id." > ".$row->client_id,
	                    'client_id' => $row->client_id,
	                    'email' => $row->email, 
	                    'name' => $row->name, 
	                    'company_name' => $row->company_name, 
	                    'recommended' => $row->recommended, 
	                    'mobile' => $row->mobile, 
	                    'home_phone' => $row->home_phone, 
	                    'home_address' => $row->home_address, 
	                    'fax' => $row->fax, 
	                    'importance' => $row->importance != 0 ? $impo_s[$row->importance] : $row->importance, 
	                    'home_address' => $row->home_address, 
	                    'company_address' => $row->company_address,
                        'company_phone' => $row->company_phone,
	                    'broker' => $broker_name));
						
	
	            $jsonData['rows'][] = $entry;
			}
        }


		

        echo json_encode($jsonData);

        //echo json_encode($client);
    }


	

    public function test_sch_client(){
      


    }


    public function customer_source_seslove($c_s){

      $this->load->model("customer_source_model");
      $res=$this->customer_source_model->get_all();
      $p = array();

      $c_s_str = explode(",",$c_s);

      foreach($res as $dat ){
        foreach($c_s_str as $_key => $_val):

          if(trim($_val)==$dat->value){
            $p[$dat->customer_source_id]=$dat->value;
          }

        endforeach;
      }
      return $p;
      //print_r($p);

    }

    public function get_all_clients() {

        $this->load->model("users_model");
        $clients = $this->users_model->get_all_users();

        $p = array();
        foreach ($clients as $client) {
            $p[$client->users_id] = $client->name;
        }
        //print_r($p);
        return $p;
    }

    public function s_pur() {
        $this->load->library('show_test');
        if (!$this->show_test->is_broker_visible()) {
            echo 'asdasd';
        }
    }

    public function users_josn() {
        $this->load->model('users_model');
        $query = trim($this->input->get('query'));
        $users = $this->users_model->get_users($query);
        echo urldecode(json_encode($users));
    }

    public function company_name_josn() {
        $this->load->model('client_model');
        $query = trim($this->input->get('query'));
        $company = $this->client_model->get_company($query);
        //print_r($company);
        //echo $this->db->last_query();echo "<br/>";
        echo urldecode(json_encode($company));
    }

    public function importance_josn() {
        $this->load->model('importance_of_customers_model');
        $query = trim($this->input->get('query'));
        //echo $query;echo "<br/>";
        $importance_of_customers = $this->importance_of_customers_model->get_not_in($query);
        //echo $this->db->last_query();echo "<br/>";
        echo urldecode(json_encode($importance_of_customers));
    }

    public function nationality_josn() {
        $this->load->model('nationality_model');
        $query = trim($this->input->get('query'));
        $nationality = $this->nationality_model->get_not_in($query);
        echo urldecode(json_encode($nationality));
    }

    public function customer_source_josn() {
        $this->load->model('customer_source_model');
        $query = trim($this->input->get('query'));
        $customer_source = $this->customer_source_model->get_not_in($query);
        echo urldecode(json_encode($customer_source));
    }

    public function category_josn() {
        $this->load->model('customer_type_model');
        $query = trim($this->input->get('query'));
        $category = $this->customer_type_model->get_not_in($query);
        echo urldecode(json_encode($category));
    }

    public function building_name_josn() {
        $this->load->model('building_name_model');
        $query = trim($this->input->get('query'));
        $building_name = $this->building_name_model->get_not_in($query);
        echo urldecode(json_encode($building_name));
    }

    public function client_users_field_ajax() {
        $this->load->model('client_users_field_model');
        $data['value'] = trim($this->input->POST('value'));
        $data['users_id'] = $this->session->userdata('users_id');
        $client_users_field = $this->client_users_field_model->update_data($data);
        if ($client_users_field > 0) {
            echo "Y";
        } else {
            echo "N";
        }
    }

    public function resolve($query_condition, $type = "") {
        $keyword = "";
        $where = array();
        $e = explode('%%', $query_condition);
        if (count($e) > 1) {
            $e0 = explode('|', $e[0]);
            $keyword = $e0[1];
            $e1 = explode('---', $e[1]);
            if (count($e1) > 1) {
                foreach ($e1 as $key => $val) {
                    $e2 = explode('|', $val);
                    $where[$e2[0]] = $e2[1];
                }
            } else {
                $e2 = explode('|', $val);
                $where[$e2[0]] = $e2[1];
            }
        } else {
            $e1 = explode('---', $e[0]);
            if (count($e1) > 1) {
                foreach ($e1 as $key => $val) {
                    $e2 = explode('|', $val);
                    $where[$e2[0]] = $e2[1];
                }
            } else {
                if ($e[0] != "") {
                    $e2 = explode('|', $e[0]);
                    $where[$e2[0]] = $e2[1];
                }
            }
        }
        if ($type == "where")
            return $where;
        else
            return $keyword;
    }

    public function data_query_results_crid($sequence = null) {

        $html = $this->init("客戶資料查詢结果", "jquery,client,pagination,table", "table");
        $this->load->model('client_field_model');
        $html["client_field"] = $this->client_field_model->get_all();
        $this->load->model('client_users_field_model');
        $cuf = $this->client_users_field_model->get_users_field($this->session->userdata('users_id'));
        if (is_object($cuf) && $cuf->value != "")
            $html["client_users_field"] = $cuf->value;
        else
            $html["client_users_field"] = ",name,company_name,mobile,home_phone,company_phone,fax,importance,home_address,cu_company,company_address,broker,";
        //echo $html["client_users_field"];
        $this->load->model('client_model');
        $this->load->model('importance_of_customers_model');
        $html["importance_of_customers"] = $this->importance_of_customers_model->get_importance();
        $this->load->model('nationality_model');
        $html["nationality"] = $this->nationality_model->get_nationality();
        $this->load->model('customer_source_model');
        $html["customer_source"] = $this->customer_source_model->get_customer_source();
        $keyword = $this->input->post('keywords');
        $where = array();
        if ($this->input->post('name') != "")
            $where['name'] = $this->input->post('name');
        if ($this->input->post('recommended') != "")
            $where['recommended'] = $this->input->post('recommended');
        if ($this->input->post('importance') != "") {
            $where['importance'] = $this->input->post('importance');
            $v = explode(",", $where['importance']);
            $q = array();
            foreach ($v as $key => $val) {
                if (trim($val) != '')
                    $q[$key] = array_search(trim($val), $html["importance_of_customers"]);
            }
            $where['importance'] = $q;
        }
        //print_r($where['importance']);
        if ($this->input->post('nationality') != "") {
            $where['nationality'] = $this->input->post('nationality');
            $v = explode(",", $where['nationality']);
            $q = array();
            foreach ($v as $key => $val) {
                if (trim($val) != '')
                    $q[$key] = array_search(trim($val), $html["nationality"]);
            }
            $where['nationality'] = $q;
        }

        if ($this->input->post('home_address') != "")
            $where['home_address'] = $this->input->post('home_address');
        if ($this->input->post('building_name') != "")
            $where['home_building_name'] = $this->input->post('building_name');
        if ($this->input->post('company_name') != "")
            $where['company_name'] = $this->input->post('company_name');
        if ($this->input->post('type_of_company') != "")
            $where['type_of_company'] = $this->input->post('type_of_company');
        if ($this->input->post('mobile') != "") {
            $where['mobile'] = trim($this->input->post('mobile'));
        }
        if ($this->input->post('customer_source') != "") {
            $where['customer_source'] = $this->input->post('customer_source');
            $v = explode(",", $where['customer_source']);
            $q = array();
            foreach ($v as $key => $val) {
                if (trim($val) != '')
                    $q[$key] = array_search(trim($val), $html["customer_source"]);
            }
            $where['customer_source'] = $q;
        }
        if ($this->input->post('sctime') != "")
            $where['sctime'] = $this->input->post('sctime');
        if ($this->input->post('ectime') != "")
            $where['ectime'] = $this->input->post('ectime');
        if ($this->input->post('sbirthday') != "")
            $where['sbirthday'] = $this->input->post('sbirthday');
        if ($this->input->post('ebirthday') != "")
            $where['ebirthday'] = $this->input->post('ebirthday');
        if ($this->input->post('send_publication') != "")
            $where['send_publication'] = $this->input->post('send_publication');
        if ($this->input->post('send_email') != "")
            $where['send_email'] = $this->input->post('send_email');
        if ($this->input->post('gifts') != "")
            $where['gifts'] = $this->input->post('gifts');
        if ($this->input->post('broker') != "")
            $where['broker'] = $this->input->post('broker');

        $condition = "";
        foreach ($where as $key => $val) {
            if ($condition == "")
                $condition .= $key . "|" . $val;
            else
                $condition .= "---" . $key . "|" . $val;
        }
        if ($keyword != "")
            $html["query_condition"] = "keyword|" . $keyword . "%%" . $condition;
        else
            $html["query_condition"] = $condition;
        //$config['per_page'] = 15;
        //$config['total_rows'] = $this->client_model->query_client_count($where, $keyword);

        /*         * *******對的*********** */
        //$keyword='';
        $this->load->library('pagination');
        $config['base_url'] = '/client/data_query_results';
        $config['total_rows'] = $this->client_model->query_client_count($where, $keyword);
        $config['per_page'] = 15;
        $limit = $config['per_page'] . "," . $sequence;
        $this->pagination->initialize($config);
        $html["victor_page"] = $this->pagination->create_links();
        /*         * *******對的*********** */

        /*
          //echo $this->db->last_query();die();
          $config['url'] = '/client/data_query_results_ajax';
          $config['num_pages'] = ceil($config['total_rows'] / $config['per_page']);
          $limit = $config['per_page'] . ",0";
          $html['page'] = $config;
          $html['sequence'] = $sequence;
          $html['pagination_sequence'] = "/client/data_query_results_sequence_ajax";
         */

        $html["result"] = $this->client_model->query_client($where, $keyword, $limit, $sequence);
        //echo $this->db->last_query();
        $this->load->view('crid/clients_crid', $html);
    }

    public function data_query_results($sequence = null) {

        $all_se =   $this->session->all_userdata();        
        $pr     =   $this->session->userdata('purview');
        
		//print_r($all_se);
		
		
        $html = $this->init("客戶資料查詢结果", "", "");

        
        $html["nationality"] = $this->nationality_model->get_all();
		
        $html["importance_of_customers"] = $this->importance_of_customers_model->get_all();

        $html["post_data"] = $_POST;
        $this->load->view('crid/clients_crid', $html);
    }

    public function data_query_results_sequence_ajax() {
        $this->load->model('client_model');
        $this->load->model('client_field_model');
        $html["client_field"] = $this->client_field_model->get_all();
        $this->load->model('client_users_field_model');
        $cuf = $this->client_users_field_model->get_users_field($this->session->userdata('users_id'));
        if (is_object($cuf) && $cuf->value != "")
            $html["client_users_field"] = $cuf->value;
        else
            $html["client_users_field"] = ",name,company_name,mobile,home_phone,company_phone,fax,importance,home_address,cu_company,company_address,broker,";
        $this->load->model('importance_of_customers_model');
        $html["importance_of_customers"] = $this->importance_of_customers_model->get_importance();
        $config['per_page'] = 15;
        $query_condition = $this->input->post('query_condition');
        $config['url'] = '/client/data_query_results_ajax';
        $limit = $config['per_page'] . ",0";
        $html['page'] = $config;
        $sequence = $this->input->post('sequence');
        $where = $this->resolve($query_condition, "where");
        $keyword = $this->resolve($query_condition);
        $html["result"] = $this->client_model->query_client($where, $keyword, $limit, $sequence);
        $this->load->view('client_data_query_results_ajax', $html);
    }

    public function data_query_results_ajax() {
        $this->load->model('client_model');
        $this->load->model('client_field_model');
        $html["client_field"] = $this->client_field_model->get_all();
        $this->load->model('client_users_field_model');
        $cuf = $this->client_users_field_model->get_users_field($this->session->userdata('users_id'));
        if (is_object($cuf) && $cuf->value != "")
            $html["client_users_field"] = $cuf->value;
        else
            $html["client_users_field"] = ",name,company_name,mobile,home_phone,company_phone,fax,importance,home_address,cu_company,company_address,broker,";
        $this->load->model('importance_of_customers_model');
        $html["importance_of_customers"] = $this->importance_of_customers_model->get_importance();
        $config['per_page'] = 15;
        $query_condition = $this->input->post('query_condition');
        $page = $this->input->post('page');
        $sequence = $this->input->post('sequence');
        $where = $this->resolve($query_condition, "where");
        $keyword = $this->resolve($query_condition);
        $p = $config['per_page'] * ($page - 1);
        $limit = $config['per_page'] . "," . $p;
        $html["result"] = $this->client_model->query_client($where, $keyword, $limit, $sequence);
        $this->load->view('client_data_query_results_ajax', $html);
    }

    public function unicode_ajax() {
        $check = $this->input->post('unicode');
        $matches = array();
        $regex = "/^\d{8}$/";
        $Corresponding_rules = array(1, 2, 1, 2, 1, 2, 4, 1);
        $sum = 0;
        $j = 0;
        if (preg_match($regex, $check, $matches)) {
            for ($i = 0; $i < strlen($check); $i++) {
                $matches["num" . ($i + 1)] = substr($check, $i, 1);
                $matches["num" . ($i + 1)] = $matches["num" . ($i + 1)] * $Corresponding_rules[$i];
                $j = floor($matches["num" . ($i + 1)] / 10) + ($matches["num" . ($i + 1)] % 10);
                $sum += $j;
            }
            if ($sum % 10 == 0) {
                return true;
            }
            if (strcmp(substr($check, 6, 1), "7") == 0) {
                if ($sum % 10 == 9) {
                    die();
                }
            }
        } else {
            echo "N";
            die();
        }
        echo "N";
        die();
    }

    public function id_number_ajax() {
        $num = $this->input->post('id_number');
        $msg = false;
        $regex = "/^[A-Za-z][1-3][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/";
        $Corresponding_rules = array("A" => 10, "B" => 11, "C" => 12, "D" => 13, "E" => 14, "F" => 15, "G" => 16, "H" => 17, "I" => 34, "J" => 18, "K" => 19, "L" => 20, "M" => 21, "N" => 22, "O" => 35, "P" => 23, "Q" => 24, "R" => 25, "S" => 26, "T" => 27, "U" => 28, "V" => 29, "W" => 32, "X" => 30, "Y" => 31, "Z" => 33);
        $matches = array();
        $one = array();
        $l_num = 1;
        $d = array();
        $x = array();
        if (preg_match($regex, $num, $matches)) {
            for ($i = 0; $i < strlen($num); $i++) {
                $matches[$i] = substr($num, $i, 1);
                $regex = "/[A-Z]/";
                if (preg_match($regex, $matches[$i], $one)) {
                    $l_num = $Corresponding_rules[$one[0]];
                } else {
                    $d["d" . $i] = $matches[$i];
                }
            }
            for ($i = 0; $i < strlen($l_num); $i++) {
                $x["x" . ($i + 1)] = substr($l_num, $i, 1);
            }
            $y = $x["x1"] + $x["x2"] * 9 + $d["d1"] * 8 + $d["d2"] * 7 + $d["d3"] * 6 + $d["d4"] * 5 + $d["d5"] * 4 + $d["d6"] * 3 + $d["d7"] * 2 + $d["d8"] * 1 + $d["d9"] * 1;
            $remainder = $y % 10;
            if ($remainder == 0) {
                $msg = TRUE;
            } else {
                $msg = false;
            }
        } else {
            $msg = FALSE;
        }
        if (!$msg)
            echo "N";
    }

    public function data_edit($id = null) {

        if (empty($id)) {

            $id = $_GET["id"];
        }
		
		

        $html = $this->init("客戶資料編輯", "jquery,client,client_data_edit_ready,date,address", "form");

        
        $html["nationality"] = $this->nationality_model->get_all();

        
        $client = $this->client_model->get_client2($id);

        $html["client"] = $client->row();

        
		$html["importance_of_customers"] = $this->importance_of_customers_model->get_all();
        $html["nationality"] = $this->nationality_model->get_all();
        $this->load->model('customer_source_model');
        $html["customer_source"] = $this->customer_source_model->get_all();

        $this->load->model('building_name_model');
        $html["building_name"] = $this->building_name_model->get_all();

        $this->load->model('type_of_company_model');
        $html["type_of_company"] = $this->type_of_company_model->get_all();
        $this->load->model('title_model');
        $html["title"] = $this->title_model->get_all();
        $this->load->model('customer_type_model');
        $html["customer_type"] = $this->customer_type_model->get_all();
        $this->load->model('contact_usual_holiday_model');
        $html["contact_usual_holiday"] = $this->contact_usual_holiday_model->get_all();
        $this->load->model('address_city_model');
        $html["address_city"] = $this->address_city_model->get_all();
        $this->load->model('address_county_model');
        $html["address_county"] = $this->address_county_model->get_by_id('1');

        $this->load->model('users_model');

        $user = $this->users_model->get_all_users();

        if (!empty($html["client"]->ref_client_verify_code)) {
            $html["ref_client_verify_code"] = $html["client"]->ref_client_verify_code;
        } else {
            $html["ref_client_verify_code"] = '';
        }

        //依client的verify－code去讀取
        // contact AND relationship

        $this->load->model('client/contact', 'contact');
        $this->load->model('client/relationship', 'relationship');
        $verify_code = $html["client"]->ref_client_verify_code;

        $html["contacts"] = $this->contact->get_contact($verify_code);
        $html["relationships"] = $this->relationship->get_relationship($verify_code);



        $html["users"] = $user;
        //echo $login_user_session["role"];
        //判斷是否要送出去給小劉！！
        $login_user_session = $this->session->all_userdata();

        $html["send_to_admin"] = false;
        
        $purview = $this->role_model->get_info($login_user_session["role"]);

        if ($purview->role_name == "秘書") {

            $html["send_to_admin"] = true;
        }

        $this->load->view('client/client_data_edit', $html);

    }



    public function data_edit_submit() {

        $this->load->model('client_model');
        $id = $this->input->post('client_id');

        $data['name'] = $this->input->post('name');
        $data['english_name'] = $this->input->post('english_name');
        $data['recommended'] = $this->input->post('recommended');
        $data['importance'] = $this->input->post('importance');
        $data['nationality'] = $this->input->post('nationality');
        $data['english_name'] = $this->input->post('english_name');
        $data['sex'] = $this->input->post('sex');
        $data['mobile'] = $this->input->post('mobile');
        $data['mobile1'] = $this->input->post('mobile1');
        $data['mobile2'] = $this->input->post('mobile2');
        $data['send_sms'] = $this->input->post('send_sms');
        $data['send_sms1'] = $this->input->post('send_sms1');
        $data['send_sms2'] = $this->input->post('send_sms2');
        $data['home_phone'] = $this->input->post('home_phone');
        $data['home_phone1'] = $this->input->post('home_phone1');
        $data['home_phone2'] = $this->input->post('home_phone2');
        $data['company_phone'] = $this->input->post('company_phone');
        $data['company_phone1'] = $this->input->post('company_phone1');
        $data['company_phone2'] = $this->input->post('company_phone2');
        $data['company_phone_ext'] = $this->input->post('company_phone_ext');
        $data['company_phone_ext1'] = $this->input->post('company_phone_ext1');
        $data['company_phone_ext2'] = $this->input->post('company_phone_ext2');
        $data['email'] = $this->input->post('email');
        $data['email1'] = $this->input->post('email1');
        $data['email2'] = $this->input->post('email2');
        $data['send_email'] = $this->input->post('send_email');
        $data['send_email1'] = $this->input->post('send_email1');
        $data['send_email2'] = $this->input->post('send_email2');
        $data['fax'] = $this->input->post('fax');
        $data['fax1'] = $this->input->post('fax1');
        $data['fax2'] = $this->input->post('fax2');
        $data['customer_source'] = $this->input->post('customer_source');
        $data['home_address'] = $this->input->post('home_address');
        $data['home_address1'] = $this->input->post('home_address1');
        $data['home_address2'] = $this->input->post('home_address2');
        $data['home_building_name'] = $this->input->post('home_building_name');
        $data['home_building_name1'] = $this->input->post('home_building_name1');
        $data['home_building_name2'] = $this->input->post('home_building_name2');
        $data['home_send_publication'] = $this->input->post('home_send_publication');
        $data['home_send_publication1'] = $this->input->post('home_send_publication1');
        $data['home_send_publication2'] = $this->input->post('home_send_publication2');
        $data['company_name'] = $this->input->post('company_name');
        $data['company_name1'] = $this->input->post('company_name1');
        $data['company_name2'] = $this->input->post('company_name2');
        $data['type_of_company'] = $this->input->post('type_of_company');
        $data['type_of_company1'] = $this->input->post('type_of_company1');
        $data['type_of_company2'] = $this->input->post('type_of_company2');
        $data['unicode'] = $this->input->post('unicode');
        $data['unicode1'] = $this->input->post('unicode1');
        $data['unicode2'] = $this->input->post('unicode2');
        $data['department'] = $this->input->post('department');
        $data['department1'] = $this->input->post('department1');
        $data['department2'] = $this->input->post('department2');
        $data['title'] = $this->input->post('title');
        $data['title1'] = $this->input->post('title1');
        $data['title2'] = $this->input->post('title2');
        $data['category'] = $this->input->post('category');
        $data['category1'] = $this->input->post('category1');
        $data['category2'] = $this->input->post('category2');
        $data['company_address'] = $this->input->post('company_address');
        $data['company_address1'] = $this->input->post('company_address1');
        $data['company_address2'] = $this->input->post('company_address2');
        $data['company_building_name'] = $this->input->post('company_building_name');
        $data['company_building_name1'] = $this->input->post('company_building_name1');
        $data['company_building_name2'] = $this->input->post('company_building_name2');
        $data['company_send_publication'] = $this->input->post('company_send_publication');
        $data['company_send_publication1'] = $this->input->post('company_send_publication1');
        $data['company_send_publication2'] = $this->input->post('company_send_publication2');
        $data['company_website'] = $this->input->post('company_website');
        $data['company_website1'] = $this->input->post('company_website1');
        $data['company_website2'] = $this->input->post('company_website2');
        $data['front_man'] = $this->input->post('front_man');
        $data['head'] = $this->input->post('head');
        $data['original_broker'] = $this->input->post('original_broker');
        $data['broker'] = $this->input->post('broker');
        $data['mtime'] = time();
        $data['birthday'] = $this->input->post('birthday');
        if ($this->input->post('birthday') != "") {
            $t = explode("/", $this->input->post('birthday'));
            $data['birthday_int'] = mktime(0, 0, 0, $t[1], $t[2], $t[0]);
        }
        $data['gifts'] = $this->input->post('gifts');
        $data['id_number'] = $this->input->post('id_number');
        $data['usually_contact'] = $this->input->post('usually_contact');
        $data['usually_contact1'] = $this->input->post('usually_contact1');
        $data['usually_contact2'] = $this->input->post('usually_contact2');
        $data['usually_start_time'] = $this->input->post('usually_start_time');
        $data['usually_start_time1'] = $this->input->post('usually_start_time1');
        $data['usually_start_time2'] = $this->input->post('usually_start_time2');
        $data['usually_end_time'] = $this->input->post('usually_end_time');
        $data['usually_end_time1'] = $this->input->post('usually_end_time1');
        $data['usually_end_time2'] = $this->input->post('usually_end_time2');
        $data['holidays_contact'] = $this->input->post('holidays_contact');
        $data['holidays_contact1'] = $this->input->post('holidays_contact1');
        $data['holidays_contact2'] = $this->input->post('holidays_contact2');
        $data['holidays_start_time'] = $this->input->post('holidays_start_time');
        $data['holidays_start_time1'] = $this->input->post('holidays_start_time1');
        $data['holidays_start_time2'] = $this->input->post('holidays_start_time2');
        $data['holidays_end_time'] = $this->input->post('holidays_end_time');
        $data['holidays_end_time1'] = $this->input->post('holidays_end_time1');
        $data['holidays_end_time2'] = $this->input->post('holidays_end_time2');
        $data['background_and_features'] = $this->input->post('background_and_features');
		
		$data['sercet_level'] = $this->input->post('sercet_level');
		$data['is_public'] = $this->input->post('is_public');
		$data['important'] = $this->input->post('important');
		$data['is_see'] = $this->input->post('is_see');
        $data['mtime'] = strtotime(date("Y-m-d h:i:s"));

        $return_result = $this->client_model->update_client_two($data, $id);
        //$this->client_model->insert_client_history($data, $id);
        //echo $this->db->last_query();die();
        //echo $id;
        //print_r($data);
        if ($return_result) {
            //redirect("/client/data_query_results");
        } else {
            //redirect("/client/data_query_results");
        }
    }

    public function data_delete($id = null) {
        
        $this->load->model('client_model');
        if ($id != null) {
            $data["id"] = $id;
            $return_result = $this->client_model->del_client($data);
            //echo $this->db->last_query();die();
            if ($return_result) {
                redirect("/client/data_query_results");
            } else {
                echo "刪除失敗";
            }
        } else {
            echo "刪除失敗";
        }
    }

    public function from_submit_handle() {

        $this->load->model('client_model');
        $mass_edm = $this->input->post('mass_edm');
        $mass_sms = $this->input->post('mass_sms');
        $turn_excel = $this->input->post('turn_excel');
        if ($mass_edm) {
            $client_id = $this->client_model->get_client_email_by_id();
        } else if ($mass_sms) {
            $client_id = $this->client_model->get_client_mobile_by_id();
        }
        $c = "";

        //$pagination_select_value = $this->input->post('pagination_select_value');
        //print_r($_POST);
        //die();
        //$psv = explode(",", $pagination_select_value);

        /*
          if ($psv) {
          foreach ($psv as $key => $val) {
          if ($client_id[$val] != "") {
          if ($c == "") {
          $c.=$client_id[$val];
          } else {
          $c.="," . $client_id[$val];
          }
          }
          }
          }
         */

        $client = $this->input->post('client');

        if ($client) {
            foreach ($client as $key => $val) {
                if ($client_id[$val] != "") {
                    if ($c == "") {
                        $c .= $client_id[$val];
                    } else {
                        $c .= "," . $client_id[$val];
                    }
                }
            }
        }

        if ($mass_edm) {
            $this->session->set_flashdata('flashdata_to', $c);
            redirect("/send_edm/index");
        } else if ($mass_sms) {
            $this->session->set_flashdata('flashdata_to', $c);
            redirect("/send_sms/index");
        } else if ($turn_excel) {
            $this->session->set_flashdata('flashdata_query', $this->input->post('pagination_query_condition'));
            redirect("/client/excel");
        }
    }

    public function batch_data_delete() {
        $this->load->model('client_model');
        $client = $this->input->post('client');
        $i = 0;
        foreach ($client as $key => $val) {
            $data["id"] = $val;
            $return_result = $this->client_model->del_client($data);
            if ($return_result) {
                $i++;
            }
        }
        if ($i > 0) {
            redirect("/send_edm/index/data_query_results");
        } else {
            echo "刪除失敗";
        }
    }

    public function delete_client() {

        $this->load->model('client_model');
        @session_start();

        foreach ($_SESSION["client_page"] as $val => $one) {

            if (!empty($val))
                $this->client_model->del_client_crid($val);
        }

        if (!empty($_SESSION["client_page"])) {
            session_unset($_SESSION["client_page"]);
        }
    }

    public function delete_company() {
        $this->load->model('client_model');
        $id = $this->input->post('client_id');
        $item = $this->input->post('item');
        if ($item == "1") {
            $data['company_name1'] = "";
            $data['type_of_company1'] = "";
            $data['unicode1'] = "";
            $data['department1'] = "";
            $data['title1'] = "";
            $data['category1'] = "";
            $data['company_address1'] = "";
            $data['company_building_name1'] = "";
            $data['company_send_publication1'] = "";
            $data['company_website1'] = "";
        } else {
            $data['company_name2'] = "";
            $data['type_of_company2'] = "";
            $data['unicode2'] = "";
            $data['department2'] = "";
            $data['title2'] = "";
            $data['category2'] = "";
            $data['company_address2'] = "";
            $data['company_building_name2'] = "";
            $data['company_send_publication2'] = "";
            $data['company_website2'] = "";
        }

        $return_result = $this->client_model->update_client($data, $id);
        if ($return_result) {
            echo "1";
        } else {
            echo "0";
        }
    }

    public function excel() {

        $this->load->model('client_model');
        $this->load->model('users_model');
        $this->load->model('importance_of_customers_model');
        $this->load->model('nationality_model');


        $html["importance_of_customers"] = $this->importance_of_customers_model->get_importance();

        $html["nationality"] = $this->nationality_model->get_nationality();
        $this->load->model('customer_source_model');
        $html["customer_source"] = $this->customer_source_model->get_customer_source();
        $this->load->model('building_name_model');
        $html["building_name"] = $this->building_name_model->get_building_name();
        $this->load->model('type_of_company_model');
        $html["type_of_company"] = $this->type_of_company_model->get_type_of_company();
        $this->load->model('title_model');
        $html["title"] = $this->title_model->get_title();
        $this->load->model('customer_type_model');
        $html["customer_type"] = $this->customer_type_model->get_customer_type();
        $this->load->model('contact_usual_holiday_model');
        $html["contact_usual_holiday"] = $this->contact_usual_holiday_model->get_contact_usual_holiday();
        $query_condition = $this->session->flashdata('flashdata_query');
        $html["users"] = $this->users_model->get_all_users();
        @session_start();

        $object_ids = array();

        if (!empty($_SESSION["client_page"])) {

            foreach ($_SESSION["client_page"] as $id => $flag) {
                if ($flag == 1) {
                    $object_ids[] = $id;
                }
            }

            $demands = $object_ids;
        } else {

            $demands = false;
        }

        //print_r($demands);

        //$res = $this->client_model->do_client_excel($demands);
        //do_client_excel_all
        $res = $this->client_model->do_client_excel_all();
        $html["res"] = $res->result();
        if (!empty($_SESSION["client_page"])) {
            session_unset($_SESSION["client_page"]);
        }

        $tes_flag = false;

        $html["result"] = $this->client_model->do_client_excel_all();

        $this->load->view('excel/vclient', $html);
    }



    public function excel_all_client() {

        $this->load->model('client_model');
        $this->load->model('users_model');
        $this->load->model('importance_of_customers_model');
        $this->load->model('nationality_model');


        $html["importance_of_customers"] = $this->importance_of_customers_model->get_importance();

        $html["nationality"] = $this->nationality_model->get_nationality();
        $this->load->model('customer_source_model');
        $html["customer_source"] = $this->customer_source_model->get_customer_source();
        $this->load->model('building_name_model');
        $html["building_name"] = $this->building_name_model->get_building_name();
        $this->load->model('type_of_company_model');
        $html["type_of_company"] = $this->type_of_company_model->get_type_of_company();
        $this->load->model('title_model');
        $html["title"] = $this->title_model->get_title();
        $this->load->model('customer_type_model');
        $html["customer_type"] = $this->customer_type_model->get_customer_type();
        $this->load->model('contact_usual_holiday_model');
        $html["contact_usual_holiday"] = $this->contact_usual_holiday_model->get_contact_usual_holiday();
        $query_condition = $this->session->flashdata('flashdata_query');
        $html["users"] = $this->users_model->get_all_users();
        

        $res = $this->client_model->do_client_excel_all();
        $html["res"] = $res->result();               
        $html["result"] = $res->result();

        $this->load->view('excel/vclient', $html);
    }

    public function excel_ckecked() {

        @session_start();
        $this->load->model('client_model');
        $this->load->model('importance_of_customers_model');
        $html["importance_of_customers"] = $this->importance_of_customers_model->get_importance();
        $this->load->model('nationality_model');
        $html["nationality"] = $this->nationality_model->get_nationality();
        $this->load->model('customer_source_model');
        $html["customer_source"] = $this->customer_source_model->get_customer_source();
        $this->load->model('building_name_model');
        $html["building_name"] = $this->building_name_model->get_building_name();
        $this->load->model('type_of_company_model');
        $html["type_of_company"] = $this->type_of_company_model->get_type_of_company();
        $this->load->model('title_model');
        $html["title"] = $this->title_model->get_title();
        $this->load->model('customer_type_model');
        $html["customer_type"] = $this->customer_type_model->get_customer_type();
        $this->load->model('contact_usual_holiday_model');
        $html["contact_usual_holiday"] = $this->contact_usual_holiday_model->get_contact_usual_holiday();
        $query_condition = $this->session->flashdata('flashdata_query');

        //print_r($_SESSION["client_page"]);

        if (!empty($_SESSION["client_page"])) {

            $temp = array();
            foreach ($_SESSION["client_page"] as $id => $flag) {

                if ($flag == 1) {
                    $temp[] = $id;
                }
            }

            $clients = $temp;
        } else {
            $clients = false;
        }

        $clients_result = $this->client_model->do_client_excel($clients);

        $tes_flag = false;

        $html["result"] = $clients_result->result();
        //print_r($_SESSION);
        if (!empty($_SESSION)) {
            session_unset($_SESSION["client_page"]);
            //session_destroy();
        }
        $this->load->view('client_data_query_excel', $html);
        //redirect('');
    }

    function type_of_company() {
        $html["i"] = $this->input->post('i');
        $html["s"] = $this->input->post('s');
        $this->load->model('type_of_company_model');
        $html["data"] = $this->type_of_company_model->get_all();
        $this->load->view('type_of_company_select', $html);
    }

    function title() {
        $html["i"] = $this->input->post('i');
        $html["s"] = $this->input->post('s');
        $this->load->model('title_model');
        $html["data"] = $this->title_model->get_all();
        $this->load->view('title_select', $html);
    }

    function category() {
        $html["i"] = $this->input->post('i');
        $html["s"] = $this->input->post('s');
        $this->load->model('customer_type_model');
        $html["data"] = $this->customer_type_model->get_all();
        $this->load->view('category_select', $html);
    }

    function company_building_name() {
        $html["i"] = $this->input->post('i');
        $html["s"] = $this->input->post('s');
        $this->load->model('building_name_model');
        $html["data"] = $this->building_name_model->get_all();
        $this->load->view('company_building_name_select', $html);
    }

    function copy_client() {

        $this->load->model('client_model');
        $data["client_id"] = $this->input->post('client_id');
        $data["name"] = $this->input->post('name');
        $data["mobile"] = $this->input->post('mobile');
        $data["home_phone"] = $this->input->post('home_phone');
        $data["recommended"] = $this->input->post('recommended');
		
        $return_result = $this->client_model->copy_client($data);
        
        if ($return_result) {
            echo "1";
        } else {
            echo "0";
        }

    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
